package com.learn.dao;

import com.learn.pojo.User;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/02/05
 * @description
 */
@Repository
public class UserDao {
    private static List<User> userList = new ArrayList<>();
    static {
        // 静态代码块，类加载时执行
        User user1 = new User(1, "12345678901", "12345678901");
        User user2 = new User(2, "98765432101", "98765432101");
        User user3 = new User(3, "逍遥", "10099");
        User user4 = new User(4, "boris", "10088");
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
    }
    public List<User> getAll() {
        return userList;
    }
    public Integer genrateId() {
        // stream API
        Integer maxId = userList.stream().map(user -> user.getId()).reduce((id1, id2) -> id1 > id2 ? id1 : id2).get();
        return maxId + 1;
    }
    public void insert(User user) {
        Integer id = genrateId();
        user.setId(id);
        userList.add(user);
    }

    public User getOneById(Integer id) {
        User user1 = userList.stream().filter(user -> user.getId().equals(id)).findFirst().get();
        return user1;
    }

    public void update(User user) {
        for (int i = 0; i < userList.size(); i++) {
            if(userList.get(i).getId().equals(user.getId())) {
                userList.set(i, user);
                return;
            }
        }
    }

    public void deleteById(Integer id) {
        for (int i = 0; i < userList.size(); i++) {
            if(userList.get(i).getId().equals(id)) {
                userList.remove(i);
                return;
            }
        }
    }
}
